//
//  CubeLandingViewController.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-6.
//
//

#import "CubeLandingViewController.h"
#import <ChamleonSDK/ChamleonSDK.h>
#import "CubeModule.h"
#import "CubesModel.h"
#import "DataCenter+Cube.h"
#import "BSLCubeConstant.h"
#import "ImageDownloadedView.h"
#import "CubeModuleManager.h"
#import "LandScroller.h"
#import "IsolatedStorageFile(CubeLogic).h"
#import "AsyncTask.h"


@interface CubeLandingViewController ()
-(void)backClick;
-(void)confirmClick;

-(void)initializeModel;
-(void)initialize:(CubeModel*)cubeModel;
-(void)update:(CubeModel*)model;
-(void)loadSnap:(NSString*)identifier version:(NSString*)version;
-(void)loadSnap:(NSArray*)array;
-(void)updateNotification;
@end

@implementation CubeLandingViewController

- (id)init{
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingProcess object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingSuccess object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:CubeModuleDownloadingFailed object:nil];

    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    UINavigationBar* navigationBar=[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)];
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
        navigationBar.barTintColor = [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1];
        navigationBar.translucent = NO;
        UIColor * cc = [UIColor whiteColor];
        NSDictionary * dict = [NSDictionary dictionaryWithObject:cc forKey:UITextAttributeTextColor];
        navigationBar.titleTextAttributes = dict;
    }
    else{
        [navigationBar setTintColor: [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1]];
    }
    
    UINavigationItem* navigationItem=[[UINavigationItem alloc] initWithTitle:@"模块快照"];
    navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(backClick)];
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0f)
        [navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    [navigationBar pushNavigationItem:navigationItem animated:NO];
    [self.view addSubview:navigationBar];
    
    
    float top=20.0f+CGRectGetMaxY(navigationBar.frame);
    
    imageView=[[ImageDownloadedView alloc] initWithFrame:CGRectMake(10.0f, top, 50.0f, 50.0f)];
    
    [self.view addSubview:imageView];
    
    
    
    float left=CGRectGetMaxX(imageView.frame)+10.0f;

    titleView=[[UILabel alloc] initWithFrame:CGRectMake(left, top, 190.0f-left, 30.0f)];
    titleView.numberOfLines=1;
    titleView.backgroundColor=[UIColor clearColor];
    titleView.textColor=[UIColor blackColor];
    titleView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:titleView];

    vertionView=[[UILabel alloc] initWithFrame:CGRectMake(left, CGRectGetMaxY(titleView.frame), 190.0f-left, 30.0f)];
    vertionView.numberOfLines=1;
    vertionView.backgroundColor=[UIColor clearColor];
    vertionView.textColor=[UIColor blackColor];
    vertionView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:vertionView];
    
    descView=[[UILabel alloc] initWithFrame:CGRectMake(left, CGRectGetMaxY(vertionView.frame), self.view.frame.size.width-left-20.0f, 60.0f)];
    descView.numberOfLines=0;
    descView.backgroundColor=[UIColor clearColor];
    descView.textColor=[UIColor blackColor];
    descView.font=[UIFont systemFontOfSize:11.0f];
    [self.view addSubview:descView];
    
    
    UIImage* img=[UIImage imageNamed:@"installbtnbg.png"];
    confirmButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:confirmButton];
    confirmButton.frame=CGRectMake(self.view.frame.size.width-10.0f-img.size.width*1.5f, top+20.0f, img.size.width*1.5f, img.size.height*1.5f);
    confirmButton.titleLabel.font=[UIFont systemFontOfSize:12.0f];
    [confirmButton setBackgroundImage:img forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    landScroller=[[LandScroller alloc] init];
    
    CGRect rect=landScroller.frame;
    rect.origin.y=CGRectGetMaxY(descView.frame);
    
    rect.size.width=self.view.frame.size.width;
    
    landScroller.frame=rect;
    [self.view addSubview:landScroller];
    
    progressView=[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    progressView.frame=CGRectMake(0.0f, imageView.frame.size.height-25.0f, imageView.frame.size.width, 20.0f);
    [imageView addSubview:progressView];
    
    [self initializeModel];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [task cancel];
}


#pragma mark method

-(void)initializeModel{
    
    NSArray* models=nil;
    if(self.type==1) //已安装列表
        models = [DataCenter defaultCenter].installMoudules;
    else
        models = [DataCenter defaultCenter].serviceModules;
    
    CubeModel* selectedModel = nil;
    for (CubeModel* model in models){
        if([model.identifier isEqualToString:self.identifier]){
            selectedModel = model;
            break;
        }
    }
    
    NSString* identifier=selectedModel.identifier;
    NSString* version=selectedModel.version;
    
    [self initialize:selectedModel];
    
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
    
    selectedModel = [cubeModule.cubeModuleManager findDownloadingCubeModule:self.identifier];
    
    if(selectedModel!=nil)
        [self update:selectedModel];
    
    [self loadSnap:identifier version:version];
    
}

-(void)backClick{
    [task cancel];
    task=nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)confirmClick{
    [progressView setProgress:0 animated:NO];
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];

    if (self.type == 0)  //未下载
    {
        [cubeModule.cubeModuleManager installModule:self.identifier];
    }
    else if (self.type == 1) //已下载
    {
        [cubeModule.cubeModuleManager uninstallModule:self.identifier];
        
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        
        self.type=0;
    }
    else if (self.type == 2)   //待更新
    {
        [cubeModule.cubeModuleManager updateModule:self.identifier];
    }
}

-(void)initialize:(CubeModel*)_cubeModel{
    titleView.text=[NSString stringWithFormat:@"模块标题：%@",_cubeModel.name];
    vertionView.text=[NSString stringWithFormat:@"版本号：%@",_cubeModel.version];
    descView.text=[NSString stringWithFormat:@"应用描述:\n%@",_cubeModel.releaseNote];
    [descView sizeToFit];
    CGRect rect=descView.frame;
    
    NSString* icon=[IsolatedStorageFile outputIcon:_cubeModel];
    if([_cubeModel.local length]>0){
        icon=[icon stringByReplacingOccurrencesOfString:@"../img/" withString:@"main_www/img/"];
        icon=[[NSBundle mainBundle] pathForResource:icon ofType:nil];
        UIImage* img=[UIImage imageWithContentsOfFile:icon];
        imageView.image=img;
        [imageView removeLoading];
    }
    else{
        [imageView setUrl:icon];
    }
    
    if(rect.size.height>60.0f){
        rect.size.height=60.0f;
        descView.frame=rect;
    }
    if (self.type == 0)        //未下载
    {
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        progressView.hidden=YES;
    }
    else if (self.type == 1) //已下载
    {
        [confirmButton setTitle:@"删除" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        
    }
    else if (self.type == 2)   //待更新
    {
        [confirmButton setTitle:@"更新" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
    }
    
    if ([_cubeModel.local length] > 0)
    {
        confirmButton.hidden=YES;
        progressView.hidden=YES;
    }
    
}

-(void)update:(CubeModel*)model{
    if (model.status == CubeMoudleStatusNone){
        [confirmButton setTitle:@"安装" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        self.type=0;
    }
    else if (model.status == CubeMoudleStatusFinish)
    {
        [confirmButton setTitle:@"删除" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        self.type=1;
    }
    else if (model.status == CubeMoudleStatusCanUpdate)
    {
        [confirmButton setTitle:@"更新" forState:UIControlStateNormal];
        confirmButton.enabled = YES;
        progressView.hidden=YES;
        self.type=2;
    }
    else
    {
        [confirmButton setTitle:@"安装中" forState:UIControlStateNormal];
        confirmButton.enabled = NO;
        progressView.hidden=NO;
        self.type=3;
    }
    
    int process=1-(float)model.downloadedProcess/(float)model.downloadedTotalCount;
    
    [progressView setProgress:process animated:YES];
    
}

-(void)loadSnap:(NSString*)identifier version:(NSString*)version{
    CubeModule* cubeModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
    
    [task cancel];
    __block CubeLandingViewController* objSelf=self;
    task=[cubeModule.cubeModuleManager loadSnapshotByIdentify:identifier version:version];
    __block AsyncTask* __task=task;

    [task setFinishBlock:^{
        if([__task result]!=nil)
            [objSelf loadSnap:[__task result]];
    }];
}

-(void)loadSnap:(NSArray*)array{
    task=nil;
    [landScroller setImages:array];
}

-(void)updateNotification{
    NSArray* models=nil;
    models = [DataCenter defaultCenter].installMoudules;
    CubeModel* selectedModel = nil;
    for (CubeModel* model in models){
        if([model.identifier isEqualToString:self.identifier]){
            selectedModel = model;
            break;
        }
    }
    [self update:selectedModel];

}

@end
